import socket
import threading
import serial

# 初始化串口
serial_port = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)  # 修改为 Linux 的串口路径和波特率

def handle_serial_to_socket(conn):
    """从串口读取数据并发送到客户端"""
    while True:
        if serial_port.in_waiting > 0:
            serial_data = serial_port.readline().decode().strip()
            print(f"Server: {serial_data}")
            conn.sendall(serial_data.encode())
def handle_socket_to_serial(conn):
    """从客户端接收数据并发送到串口"""
    while True:
        try:
            data = conn.recv(1024)
            if not data:
                print("Connection closed by client.")
                break
            decoded_data = data.decode()
            print(f"Received from client: {decoded_data}")

            # 在数据末尾添加换行符（LF）
            data_with_lf = f"{decoded_data}\n".encode()
            serial_port.write(data_with_lf)  # 将处理后的数据写入串口
            print(f"Sent to serial: {decoded_data} (with LF)")
        except Exception as e:
            print(f"Error in handle_socket_to_serial: {e}")
            break

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('192.168.1.113', 65432))
    s.listen()
    print("Server is listening on port 65432...")
    conn, addr = s.accept()
    print('Connected by', addr)
    with conn:
        # 创建线程分别处理串口到网络和网络到串口的通信
        serial_to_socket_thread = threading.Thread(target=handle_serial_to_socket, args=(conn,))
        socket_to_serial_thread = threading.Thread(target=handle_socket_to_serial, args=(conn,))
        serial_to_socket_thread.start()
        socket_to_serial_thread.start()

        # 等待线程结束
        serial_to_socket_thread.join()
        socket_to_serial_thread.join()